// 监听用户路由事件 劫持 重新调用reroute方法 进行计算应用的加载
import { reroute } from "./reroute.js"

function urlRoute() {
    reroute(arguments)
}

window.addEventListener('hashchange', urlRoute)
window.addEventListener('popstate', urlRoute)

const capturedEventListeners = {
    hashchange: [],
    popstate: []
}

const listentingTo = ['hashchange', 'popstate']

const originalAddEventListener = window.addEventListener
const originalRemoveEventListener = window.removeEventListener

window.addEventListener = function (eventName, callback) {
    if(listentingTo.includes(eventName)&& !capturedEventListeners[eventName].some(listen => listen === callback)){
        return capturedEventListeners[eventName].push(callback)
    }
    return originalAddEventListener.apply(this, arguments)
}

window.removeEventListener = function (eventName, callback) {
    if(listentingTo.includes(eventName)){
        capturedEventListeners[eventName] = capturedEventListeners[eventName].filter(fn => fn!==callback)
        return
    }
    return originalRemoveEventListener.apply(this, arguments)
}

export function callCaptureEventListeners(event) {
    if(event){
        const eventType = event[0]?.type
        if(listentingTo.includes(eventType)){
            capturedEventListeners[eventType].forEach(listener => {
                listener.apply(this, event)
            })
        }
    }
}

function patchFn(updateState, methodName) {
    return function () {
        const urlBefore = window.location.href
        const r = updateState.apply(this, arguments)
        const urlAfter = window.location.href
        if(urlBefore !== urlAfter){
            window.dispatchEvent(new PopStateEvent("popstate"))
        }
        return r
    }
}

window.history.pushState = patchFn(window.history.pushState, 'pushState')

window.history.replaceState = patchFn(window.history.replaceState, 'replaceState')